package fnord.network.server;

import java.io.IOException;
import java.io.Serializable;
import java.util.List;

import fnord.exception.BadCardException;
import fnord.exception.BadPortException;
import fnord.exception.MapLoaderException;
import fnord.illuminati.Board;
import fnord.illuminati.order.Order;
import fnord.network.OrderType;

public class Server {
	
	private ServerCommunicator _serverCom;
	private Referee _ref;
	private int _numPlayers;
	
	public Server(int numPlayers, int port) throws BadPortException, IOException, MapLoaderException {
		_serverCom = new ServerCommunicator(this, port);
		_ref = new Referee(this);
		_numPlayers = numPlayers;
//		System.out.println("I am your server.");
//		System.out.println("working on "+_serverCom.getPort());
	}
	
	public void getClients() throws IOException {
		List<Player> players = _serverCom.getClients(_numPlayers, _ref);
		try {
			_ref.enactTurn(players.get(0));
		} catch (BadCardException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	public void sendState(Board board) {
		_serverCom.sendData(OrderType.GAME_STATE, board, null);
		
	}

	public void sendErrorToPlayer(Player player, String string) {
		//_serverCom.sendData(OrderType.ERROR, string, player);
		
	}

	public void sendChat(Serializable readObject) {
//		System.out.println("server says "+((String)readObject));

		_serverCom.sendData(OrderType.CHAT, readObject, null);
		
	}

	public void putOrder(ClientListenerThread clt, Order toPut) {
		_serverCom.putOrder(clt, toPut);
	}
	
	public Order getOrder(Player fromPlayer) {
		return _serverCom.getLastOrder(fromPlayer);
	}


	public boolean isGood() {
		return _serverCom.isOpen();
	}


	public int getPort() {
		return _serverCom.getPort();
	}

	public void quitClient(ClientListenerThread clientListenerThread) {
		Player p = _serverCom.closePlayer(clientListenerThread);
		if(p != null) {
			_ref.dropPlayer(p);
		}
	}
	
	public void sendQuit() {
		_serverCom.sendData(OrderType.QUIT, null, null);
	}

}
